package com.loveprogrammer.eternity.factory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.loveprogrammer.eternity.factory.template.MapTemplate;
import com.loveprogrammer.eternity.factory.template.NPCTemplate;
import com.loveprogrammer.eternity.model.npc.NPC;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName NPCFactory
 * @Description
 * @Author eric
 * @Date 2023/8/7 14:55
 * @Version 1.0
 */
public class NPCFactory {

    private static List<NPCTemplate> npcTemplates;
    private static Map<String,NPCTemplate> npcMap;

    // 初始化npc模版
    static {
        try {
            // 读取配置文件，然后加载到weaponTemplates中
            ClassLoader classLoader = EquipmentFactory.class.getClassLoader();
            InputStream inputStream = classLoader.getResourceAsStream("npc.json");

            assert inputStream != null;
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            StringBuilder responseStrBuilder = new StringBuilder();

            String inputStr;
            while ((inputStr = streamReader.readLine()) != null)
                responseStrBuilder.append(inputStr);

            npcTemplates = JSONArray.parseArray(responseStrBuilder.toString(), NPCTemplate.class);
            npcMap = npcTemplates.stream().collect(Collectors.toMap(e -> e.getId(), e -> e));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        for (NPCTemplate template : npcTemplates) {
            System.out.println(JSON.toJSONString(template));
        }
    }


    public static List<NPC> batchAddNPC(List<String> npcIds){
        List<NPC> result = new ArrayList<>();
        for (String npcId : npcIds) {
            result.add(TemplateToInstance(npcMap.get(npcId)));
        }
        return result;
    }

    private static NPC TemplateToInstance(NPCTemplate npcTemplate) {
        NPC npc = new NPC();
        npc.setName(npcTemplate.getName());
        npc.setId(npcTemplate.getId());
        npc.setBackground(npcTemplate.getBackground());
        npc.setDialogues(npcTemplate.getDialogues());

        return npc;
    }
}
